package com.rongzhe.house.order.service;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.mapper.Condition;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rongzhe.house.bill.entity.Bill;
import com.rongzhe.house.bill.mapper.BillMapper;
import com.rongzhe.house.common.exception.RongZheBusinessException;
import com.rongzhe.house.common.resp.ApiResult;
import com.rongzhe.house.common.utils.AliPayUtil;
import com.rongzhe.house.common.utils.DateUtil;
import com.rongzhe.house.common.utils.HouseESUtil;
import com.rongzhe.house.common.utils.SnowFlakeIdWorker;
import com.rongzhe.house.dictionary.enums.DictEnums;
import com.rongzhe.house.dictionary.service.DictService;
import com.rongzhe.house.easypoi.dto.RentInfoDTO;
import com.rongzhe.house.easypoi.handler.HouseContractHandler;
import com.rongzhe.house.house.dao.HouseBaseMapper;
import com.rongzhe.house.house.dao.HouseConfigMapper;
import com.rongzhe.house.house.dao.HouseRoomLiveInfoMapper;
import com.rongzhe.house.house.entity.HouseBase;
import com.rongzhe.house.house.entity.HouseConfig;
import com.rongzhe.house.house.entity.HouseDetail;
import com.rongzhe.house.house.entity.HouseRoomLiveInfo;
import com.rongzhe.house.house.enums.HouseBaseRentStatus;
import com.rongzhe.house.house.es_repository.ESHouse;
import com.rongzhe.house.order.constants.ResponseCode;
import com.rongzhe.house.order.criteria.OrderCriteria;
import com.rongzhe.house.order.dao.ItemMapper;
import com.rongzhe.house.order.dao.OrderBillInfoMapper;
import com.rongzhe.house.order.dao.OrderMapper;
import com.rongzhe.house.order.dao.OrderSnapshotMapper;
import com.rongzhe.house.order.entity.*;
import com.rongzhe.house.order.enums.OrderStatus;
import com.rongzhe.house.order.enums.OrderType;
import com.rongzhe.house.order.enums.PayType;
import com.rongzhe.house.pay.WxpayService;
import com.rongzhe.house.pay.entity.WeiXinNotify;
import com.rongzhe.house.pay.entity.WeixinOrder;
import com.rongzhe.house.user.dao.UserBaseMapper;
import com.rongzhe.house.user.dao.UserContractMapper;
import com.rongzhe.house.user.dao.UserIdentifyCardInfoMapper;
import com.rongzhe.house.user.entity.UserContract;
import com.rongzhe.house.user.entity.UserIdentifyCardInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutionException;

/**
 * Created by hggxg on 2017/11/19.
 */
@Service
public class OrderServiceImpl implements OrderService {


    @Autowired
    private OrderMapper orderMapper;


    @Autowired
    private AliPayUtil aliPayUtil;

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private HouseBaseMapper houseBaseMapper;

    @Autowired
    private HouseConfigMapper houseConfigMapper;

    @Autowired
    private OrderSnapshotMapper orderSnapshotMapper;

    @Autowired
    private HouseRoomLiveInfoMapper houseRoomLiveInfoMapper;


    @Autowired
    private UserContractMapper userContractMapper;

    @Autowired
    private DictService dictService;

    @Autowired
    private UserIdentifyCardInfoMapper userIdentifyCardInfoMapper;

    @Autowired
    private HouseESUtil houseESUtil;

    @Autowired
    private BillMapper billMapper;

    @Autowired
    private OrderBillInfoMapper orderBillInfoMapper;

    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private HouseContractHandler houseContractHandler;

    @Override
    public List<Order> list(OrderCriteria orderCriteria) {

        PageHelper.startPage(orderCriteria.getCurrentPage(), orderCriteria.getPageSize());

        PageHelper.orderBy("o.insert_time DESC");

        PageInfo<Order> pageInfo = new PageInfo(orderMapper.selectByCriteria(orderCriteria));

        List<Order> orders = pageInfo.getList();

        if (!CollectionUtils.isEmpty(orders)) {
            for (Order order : orders) {
                if (null != order.getSnapshot()) {
                    OrderSnapshotContent content = JSON.parseObject(order.getSnapshot(), OrderSnapshotContent.class);
                    order.setSnapshot(null);
                    HouseDetail houseDetail = houseBaseMapper.selectDetailByIdc(Integer.valueOf(content.getHouseId()));
                    content.setName(houseDetail.getName());
                    content.setOrientation(houseDetail.getOrientation());
                    content.setRoomNum(houseDetail.getRoomNum());
                    order.setContent(content);
                }

            }
        }

        return orders;
    }

    @Override
    public Order detail(OrderCriteria orderCriteria) {

        Order order = orderMapper.detailByOrderCode(orderCriteria.getOrderCode());

        order.setContent(JSON.parseObject(order.getSnapshot(), OrderSnapshotContent.class));
        order.setSnapshot(null);

        UserContract userContract = userContractMapper.selectByOrderCode(order.getCode());

        order.setUserContract(userContract);

        UserIdentifyCardInfo userIdentifyCardInfo = userIdentifyCardInfoMapper.selectByUid(order.getCreateUid());
        order.setUserIdentifyCardInfo(userIdentifyCardInfo);


        return order;
    }

    @Transactional
    @Override
    public String createOrder(Integer itemId, Integer count, Integer uid) throws RongZheBusinessException {
        //1 查询房屋租金 锁住
        Item item = itemMapper.selectByPrimaryKeyForUpdate(itemId);

        HouseDetail houseDetail = houseBaseMapper.selectDetailById(item.getBizId());

        //判断房源换房源是否可以 继续创建订单操作
        if (houseDetail.getRentStatus().equals(HouseBaseRentStatus.LOCK.getStatus())) {
            throw new RongZheBusinessException("房源已被锁定");
        }


        if (houseDetail.getRentStatus().equals(HouseBaseRentStatus.CAN_NOT_ENTER.getStatus())) {
            throw new RongZheBusinessException("房源已出租");
        }


        //房锁住
        HouseBase houseBaseUpdate = new HouseBase();
        houseBaseUpdate.setId(houseDetail.getId());
        houseBaseUpdate.setRentStatus((byte) HouseBaseRentStatus.LOCK.getStatus());
        houseBaseMapper.updateByPrimaryKeySelective(houseBaseUpdate);


        //2 根据数量计算总金额

        BigDecimal price = item.getPrice();

        BigDecimal totalPrice = price.multiply(new BigDecimal(count));


        //3 创建订单，返回订单信息（订单号，商品名称，图片，金额）

        Order order = new Order();

        order.setAmount(totalPrice);
        order.setBizId(itemId);
        order.setInsertUid(uid);
        order.setCreateUid(uid);
        order.setInsertTime(new Date());
        //TODO 魔数
//        order.setDeleted((byte) 1);
        order.setCode(SnowFlakeIdWorker.getId());
        order.setCreateTime(new Date());
        order.setStatus(OrderStatus.WAIT_PAY.getStatus());
        order.setRemark(item.getName());

        orderMapper.insertSelective(order);

        //不修改房源状态，只有支付之后再修改房源状态

        //4 修改房源状态
//        Item item = itemMapper.selectByPrimaryKey(itemId);

        Integer houseId = item.getBizId();


//        HouseDetail houseDetail = houseBaseMapper.selectDetailById(houseId);

        //保存商品快照
        OrderSnapshotContent orderSnapshotContent = new OrderSnapshotContent();
        orderSnapshotContent.setHouseId(houseId.toString());
        orderSnapshotContent.setCover(houseDetail.getCover());
        orderSnapshotContent.setPrice(houseDetail.getRent());
        orderSnapshotContent.setName(houseDetail.getName());
        orderSnapshotContent.setRegionName(houseDetail.getRegionName());
        orderSnapshotContent.setRegionFinalName(houseDetail.getRegionFinalName());

        ItemExt itemExt = JSON.parseObject(item.getExt(), ItemExt.class);

        Map<String, String> map = dictService.getMapByParentCode(DictEnums.House_Rent_Pay_Type.getCode());

        orderSnapshotContent.setRentPayment(map.get(itemExt.getRentOption()));
        orderSnapshotContent.setPledge(itemExt.getPledge());
        orderSnapshotContent.setServiceFee(itemExt.getServiceFee());

        OrderSnapshot orderSnapshot = new OrderSnapshot();
        orderSnapshot.setSnapshot(JSON.toJSONString(orderSnapshotContent));
        orderSnapshot.setOrderCode(order.getCode());

        orderSnapshotMapper.insertSelective(orderSnapshot);

        return order.getCode();
    }

    @Transactional
    @Override
    public String createBillsOrder(List<CreateRequest> createRequests, Integer uid) {
        BigDecimal totalPrice = new BigDecimal(0.00);
        String code = SnowFlakeIdWorker.getId();

        for (CreateRequest createRequest : createRequests) {
            Bill bill = billMapper.selectById(createRequest.getBillId());
            //根据数量计算总金额
            BigDecimal price = bill.getPayable();
            totalPrice = totalPrice.add(price);
            OrderBillInfo orderBillInfo = new OrderBillInfo();
            orderBillInfo.setBillId(bill.getId());
            orderBillInfo.setOrderCode(code);
            orderBillInfo.setInsertTime(new Date());
            orderBillInfo.setInsertUid(uid);
            orderBillInfoMapper.insert(orderBillInfo);
        }

        //创建订单，返回订单信息（订单号，商品名称，图片，金额）
        Order order = new Order();
        order.setAmount(totalPrice);
        order.setBizId(null);
        order.setInsertUid(uid);
        order.setCreateUid(uid);
        order.setInsertTime(new Date());
        order.setCode(code);
        order.setCreateTime(new Date());
        order.setStatus(OrderStatus.WAIT_PAY.getStatus());
        order.setRemark("多款账单支付");
        order.setType(OrderType.Bill.getType());//账单

        orderMapper.insertSelective(order);

        return code;
    }

    @Override
    public ApiResult<String> showContract(Integer itemId, Integer userId) {
        return this.showContract(itemId, userId, true);
    }


    private ApiResult showContract(Integer itemId, Integer userId, boolean flag) {
        RentInfoDTO rentInfoDTO = new RentInfoDTO();
        RentInfo rentInfo = userBaseMapper.selectRentInfoByUserId(userId);
        Integer id = rentInfo.getId();
        if (Objects.isNull(id)) {
            return ApiResult.buildFail("该用户暂时未实名认证,请实名认证后再试");
        }
        String state = rentInfo.getState();
        if (!"2".equals(state)) {
            return ApiResult.buildFail("该用户暂时未实名认证,请实名认证后再试");
        }
        rentInfoDTO.setRentName(rentInfo.getRealName());
        rentInfoDTO.setRentSex("1".equals(rentInfo.getSex()) ? "男" : "女");
        rentInfoDTO.setCertificateNo(rentInfo.getIdentifyCardNum());
        rentInfoDTO.setCertificateImage1(rentInfo.getIdentifyCardImageFront());
        rentInfoDTO.setCertificateImage2(rentInfo.getIdentifyCardImageBack());
        rentInfoDTO.setRentMobile(rentInfo.getMobile());


        //1 查询房屋租金 锁住
        Item item = itemMapper.selectByPrimaryKeyForUpdate(itemId);
        ItemExt itemExt = JSON.parseObject(item.getExt(), ItemExt.class);

        Integer houseId = item.getBizId();

        HouseBase houseBase = houseBaseMapper.selectByPrimaryKey(houseId);
        String address = houseBaseMapper.selectAdress(houseId);
        rentInfoDTO.setArea(houseBase.getArea().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        rentInfoDTO.setHouseAddress(address);
        String rongzheAddress = houseBaseMapper.selectRongzheAddressById(houseId);
        rentInfoDTO.setRongzheAddress(rongzheAddress);

        rentInfoDTO.setHouseId(houseId);
        Date date = new Date();
        rentInfoDTO.setRentStart(date);
        Date date1 = DateUtil.addYears(date, 1);
        Date date2 = DateUtil.addDays(date1, -1);
        rentInfoDTO.setRentEnd(date2);

        rentInfoDTO.setRentTerm("一年");
        rentInfoDTO.setPayMethod(item.getName());
        rentInfoDTO.setDeposit(itemExt.getPledge());
        rentInfoDTO.setMonthFee(itemExt.getServiceFee());
        rentInfoDTO.setMonthRent(itemExt.getRent());
        String rentOption = itemExt.getRentOption();
        switch (rentOption) {
            case "1":
                rentInfoDTO.setPayCount("12");
                break;
            case "2":
                rentInfoDTO.setPayCount("4");
                break;
            case "3":
                rentInfoDTO.setPayCount("2");
                break;
            case "4":
                rentInfoDTO.setPayCount("1");
                break;
            default:
                rentInfoDTO.setPayCount("12");
        }
        HouseConfig houseConfig = houseConfigMapper.selectByHouseId(houseId);
        if (Objects.nonNull(houseConfig)) {
            StringBuilder sb = new StringBuilder("房间配置包括");
            if (houseConfig.getBed().intValue() == 1) {
                sb.append("床 ");
            }
            if (houseConfig.getWardrobe().intValue() == 1) {
                sb.append("衣柜 ");
            }
            if (houseConfig.getWardrobe().intValue() == 1) {
                sb.append("书桌 ");
            }
            if (houseConfig.getDesk().intValue() == 1) {
                sb.append("衣柜 ");
            }
            if (houseConfig.getWifi().intValue() == 1) {
                sb.append("wifi ");
            }
            if (houseConfig.getWashwheel().intValue() == 1) {
                sb.append("洗衣机 ");
            }
            if (houseConfig.getHeater().intValue() == 1) {
                sb.append("热水器 ");
            }
            if (houseConfig.getAirCondition().intValue() == 1) {
                sb.append("空调 ");
            }
            if (houseConfig.getMicrowaveOven().intValue() == 1) {
                sb.append("微波炉 ");
            }
            rentInfoDTO.setPublicList(sb.toString());
        }

        if (flag) {
            return houseContractHandler.previewContract(rentInfoDTO);
        } else {
            return houseContractHandler.longTermContract(rentInfoDTO);
        }
    }

    @Transactional
    @Override
    public String createCustomOrder(Integer billId, Integer count, Integer uid) throws RongZheBusinessException {
        Bill bill = billMapper.selectById(billId);
        //根据数量计算总金额
        BigDecimal price = bill.getPayable();
        BigDecimal totalPrice = price.multiply(new BigDecimal(count));

        //创建订单，返回订单信息（订单号，商品名称，图片，金额）
        Order order = new Order();
        order.setAmount(totalPrice);
        order.setBizId(billId);
        order.setInsertUid(uid);
        order.setCreateUid(uid);
        order.setInsertTime(new Date());
        order.setCode(SnowFlakeIdWorker.getId());
        order.setCreateTime(new Date());
        order.setStatus(OrderStatus.WAIT_PAY.getStatus());
        order.setRemark(bill.getName());
        order.setType(OrderType.Bill.getType());//账单 订单

        orderMapper.insertSelective(order);
        return order.getCode();

    }

    @Transactional
    @Override
    public ApiResult getSign(String orderCode, PayType payType) throws AlipayApiException {
        //1 根据订单号，后去获取订单，判断订单状态

        Order order = orderMapper.selectByCodeForUpdate(orderCode);

        if (order == null) {
            return null;
        }
        if (!order.getStatus().equals(OrderStatus.WAIT_PAY.getStatus())) {
            return new ApiResult(ResponseCode.PAID, ResponseCode.getMessage(ResponseCode.PAID));
        }


        //2 根据选择的支付方式，获取第三方签名
        if (payType.isAliPay()) {
            String[] arr;

            arr = aliPayUtil.orderCreate(order);

            Order orderUpdate = new Order();
            orderUpdate.setCode(orderCode);
            orderUpdate.setOutTradeNo(arr[1]);
            orderUpdate.setPayment((byte) payType.getType());
            orderMapper.updateByCode(orderUpdate);
            //3 返回签名的内容
            return new ApiResult(arr[0]);
        }
        if (payType.isWx()) {
            WeixinOrder weixinOrder = new WeixinOrder();
            weixinOrder.setBody("荣者租房");
            weixinOrder.setOut_trade_no(order.getCode());
            //只能是分
            weixinOrder.setTotal_fee(order.getAmount().multiply(new BigDecimal(100)).intValue());
            return new ApiResult<>(wxpayService.precreate(weixinOrder));
        }


        return new ApiResult();
    }

    @Autowired
    private WxpayService wxpayService;

    @Override
    public String wxCallback(WeiXinNotify weiXinNotify) {

        //1 根据订单号获取订单 TODO

        //2 判断订单状态(行锁)

        //3 根据判断结果返回微信状态

        return null;
    }

    @Override
    public ApiResult query(String orderCode) {

        //1 根据订单号获取订单
        Order order = orderMapper.selectByCodeForUpdate(orderCode);

        if (order == null) {
            return null;
        }
        //2 判断订单状态(行锁)
        if (!order.getStatus().equals(OrderStatus.WAIT_PAY)) {
            return new ApiResult(ResponseCode.PAID, ResponseCode.getMessage(ResponseCode.PAID));
        }


        //3 如果支付，则返回 true。 未支付， 则查询微信服务器（由于回调失败，主动查询微信那边的订单状态）

        //4 根据微信的返回值，调用上面的wxCallback 方法

        //5 如果第4步成功状态，返回true。  失败 false

        return new ApiResult();
    }


    @Transactional
    @Override
    public void paid(String orderCode, String out_trade_no, int type) {
        //1 根据订单号获取订单
        Order order = orderMapper.selectByCodeForUpdate(orderCode);

        if (order == null) {
            return;
        }
        //2 判断订单状态(行锁)
        if (!order.getStatus().equals(OrderStatus.WAIT_PAY.getStatus())) {
            return;
        }


        if (OrderType.HouseRent.getType().equalsIgnoreCase(order.getType())) {
            //租房
            //3 支付完成，修改订单状态
            houseRentPaidWrap(orderCode, out_trade_no, order, type);


        } else if (OrderType.Bill.getType().equalsIgnoreCase(order.getType())) {
            //支付成功  修改账单状态
            billPaidWrap(orderCode, out_trade_no, order, type);
        } else {

        }

    }

    private void billPaidWrap(String orderCode, String out_trade_no, Order order, int type) {
        //修改订单
        updateOrderPaid(orderCode, out_trade_no, type);
        //修改账单
        List<OrderBillInfo> list = orderBillInfoMapper.selectList(Condition.create().eq("order_code", orderCode));
        for (OrderBillInfo orderBillInfo : list) {
            Bill bill = billMapper.selectById(orderBillInfo.getBillId());
            Date curr = new Date();
            bill.setUpdateTime(curr);
            bill.setReceived(bill.getPayable());
            bill.setReceivedDate(curr);
            bill.setStatus("2");//已收款
            billMapper.updateById(bill);
            //修改子账单信息
            List<Bill> data = billMapper.selectList(Condition.create().setSqlSelect("id", "status", "payable")
                    .eq("parent_id", bill.getId()));
            if (null != data) {
                for (Bill b : data) {
                    b.setUpdateTime(new Date());
                    b.setReceived(b.getPayable());
                    if (b.getStatus().equals("1")) {
                        b.setStatus("2");
                        b.setReceivedDate(bill.getReceivedDate());
                    }
                    billMapper.updateById(b);
                }
            }

        }

    }

    /**
     * 支付完成 订单公共修改状态
     *
     * @param orderCode
     * @param out_trade_no
     * @param type
     * @return
     */
    private Order updateOrderPaid(String orderCode, String out_trade_no, int type) {
        Order orderForUpdate = new Order();
        orderForUpdate.setCode(orderCode);
        orderForUpdate.setStatus(OrderStatus.PAID.getStatus());
        orderForUpdate.setOutTradeNo(out_trade_no);
        orderForUpdate.setPaidTime(new Date());
        orderForUpdate.setPayment((byte) type);
        orderMapper.updateByCode(orderForUpdate);
        return orderForUpdate;
    }

    private void houseRentPaidWrap(String orderCode, String out_trade_no, Order order, int type) {
        //修改订单状态
        updateOrderPaid(orderCode, out_trade_no, type);

        Integer itemId = order.getBizId();

        //4 修改房源状态
        Item item = itemMapper.selectByPrimaryKey(itemId);

        Integer houseId = item.getBizId();

//        HouseBase houseBaseSelect = houseBaseMapper.selectByPrimaryKey(houseId);

        //整租
//        if (houseBaseSelect.getIsEntireRent() == (byte) 1) {

        HouseBase houseBase = new HouseBase();
        houseBase.setId(houseId);
        houseBase.setRentStatus((byte) HouseBaseRentStatus.CAN_NOT_ENTER.getStatus());
        houseBaseMapper.updateByPrimaryKeySelective(houseBase);

        //TODO 默认一年

        UserContract userContract = new UserContract();


        ApiResult apiResult = this.showContract(itemId, order.getCreateUid(), false);
        if ("200".equals(apiResult.getCode())) {
            userContract.setContractUrl(apiResult.getData().toString());
            userContract.setConfirm("1");
            userContract.setEleContract(1);
        }

        userContract.setHouseId(item.getBizId());
        userContract.setUid(order.getCreateUid());

        Calendar date = Calendar.getInstance();

        userContract.setStartTime(date.getTime());

        date.add(Calendar.YEAR, 1);

        userContract.setOrderCode(orderCode);

        userContract.setEndTime(date.getTime());
        userContract.setInsertTime(new Date());
        userContractMapper.insertSelective(userContract);

        HouseRoomLiveInfo houseRoomLiveInfo = new HouseRoomLiveInfo();
        houseRoomLiveInfo.setHouseId(houseId);
        houseRoomLiveInfo.setLiveUid(order.getCreateUid());
        houseRoomLiveInfo.setInsertTime(new Date());
        houseRoomLiveInfo.setStartTime(userContract.getStartTime());
        HouseRoomLiveInfo houseRoomLiveInfoDb = houseRoomLiveInfoMapper.selectByHouseId(houseId);

        if (houseRoomLiveInfoDb == null) {
            houseRoomLiveInfoMapper.insertSelective(houseRoomLiveInfo);
        } else {
            //修改当前住的人
            houseRoomLiveInfoDb.setLiveUid(order.getCreateUid());
            houseRoomLiveInfoMapper.updateByPrimaryKey(houseRoomLiveInfoDb);
        }


        //支付成功修改支付状态
        ESHouse esHouse = new ESHouse();
        esHouse.setId(order.getBizId());

        esHouse.setRentStatus("2");

        try {
            houseESUtil.updateHouseEsWrap(esHouse);
        } catch (IOException e) {
            //记录异常 TODO
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        //生成账单


        List<Item> items = itemMapper.selectByHouseId(houseId);

        ItemExt currentItem = JSON.parseObject(item.getExt(), ItemExt.class);

        String currentRentOption = currentItem.getRentOption();


        Item itemFirst = null;

        Item itemAfter = null;


        for (Item i : items) {

            if (itemFirst != null && itemAfter != null) {
                break;
            }

            ItemExt ext = JSON.parseObject(i.getExt(), ItemExt.class);

            if (ext.getRentOption().equals(currentRentOption) && i.getShow()) {
                itemFirst = i;
            }
            if (ext.getRentOption().equals(currentRentOption) && !i.getShow()) {
                itemAfter = i;
            }
        }


        //6 生成周期账单
        genBill(itemFirst, userContract, itemAfter, 12);

    }


    private void genBill(Item firstItem, UserContract userContract, Item afterItem, int monthCount) {

        ItemExt itemExt = JSON.parseObject(firstItem.getExt(), ItemExt.class);

        ItemExt itemExtAfter = JSON.parseObject(afterItem.getExt(), ItemExt.class);

        int count = 0;
        //@TODO 租金浮动 （服务费为月租金的10%）
        if ("1".equals(itemExt.getRentOption())) {
            //押一付一 租金上浮5%
            count = 1;
        } else if ("2".equals(itemExt.getRentOption())) {
            //押一付三 租金不变
            count = 3;
        } else if ("3".equals(itemExt.getRentOption())) {
            //押一付六 服务费8折
            count = 6;
        } else if ("4".equals(itemExt.getRentOption())) {
            //押一付十二 服务费5折
            count = 12;
        } else {

        }


        Calendar calendar = Calendar.getInstance();
        calendar.setTime(userContract.getStartTime());
        Integer insertUid = userContract.getUid();

        Date start = new Date();

        Date date = new Date();

        //生成账单
        for (int i = 0; i < monthCount / count; i++) {
            start = calendar.getTime();
            calendar.add(Calendar.MONTH, count);
            if (i == 0) {
                wrapBills(firstItem, userContract, itemExt, start, calendar.getTime(), insertUid, date, "首次支付", count, true);
            } else {
                wrapBills(afterItem, userContract, itemExtAfter, start, calendar.getTime(), insertUid, date, "后续支付", count, false);
            }

        }

    }

    private void wrapBills(Item item, UserContract userContract, ItemExt itemExt,
                           Date start, Date end, Integer insertUid, Date date, String name, int count, boolean isFirst) {
        Bill bill = new Bill();

        bill.setBizId(userContract.getId());
        bill.setBizType("1");
        bill.setPayableDate(start);

        bill.setPayable(item.getPrice());


        bill.setName(name);
        bill.setUid(userContract.getUid());
        bill.setInsertTime(date);
        bill.setInsertUid(insertUid);

        if (isFirst) {
            bill.setStatus("2");
            bill.setReceived(item.getPrice());
            bill.setReceivedDate(start);
        }
        bill.setStartTime(start);
        bill.setEndTime(end);
        billMapper.insert(bill);

        //租金
        Bill billRent = new Bill();

        billRent.setBizId(userContract.getId());
        billRent.setBizType("1");
        billRent.setType("1");
        billRent.setPayableDate(start);
        billRent.setPayable(itemExt.getRent().multiply(new BigDecimal(count)));
        billRent.setName("租金");
        billRent.setUid(userContract.getUid());
        billRent.setInsertTime(date);
        billRent.setInsertUid(insertUid);
        billRent.setParentId(bill.getId());

        if (isFirst) {
            billRent.setStatus("2");
            billRent.setReceived(item.getPrice());
            billRent.setReceivedDate(start);
        }
        billRent.setStartTime(start);
        billRent.setEndTime(end);
        billMapper.insert(billRent);
        //押金
        if (isFirst) {
            Bill billPledge = new Bill();

            billPledge.setBizId(userContract.getId());
            billPledge.setType("2");
            billPledge.setBizType("1");
            billPledge.setPayableDate(start);
            billPledge.setPayable(itemExt.getPledge());
            billPledge.setName("押金");
            billPledge.setUid(userContract.getUid());
            billPledge.setInsertTime(date);
            billPledge.setInsertUid(insertUid);
            billPledge.setParentId(bill.getId());

            billPledge.setStatus("2");
            billPledge.setReceived(item.getPrice());
            billPledge.setReceivedDate(start);

            billPledge.setStartTime(start);
            billPledge.setEndTime(end);
            billMapper.insert(billPledge);
        }

        //服务费
        Bill billService = new Bill();
        billService.setBizId(userContract.getId());
        billService.setType("3");
        billService.setBizType("1");
        billService.setPayableDate(start);
        billService.setPayable(itemExt.getServiceFee());
        billService.setName("服务费");
        billService.setUid(userContract.getUid());
        billService.setInsertTime(date);
        billService.setInsertUid(insertUid);
        billService.setParentId(bill.getId());

        if (isFirst) {
            billService.setStatus("2");
            billService.setReceived(item.getPrice());
            billService.setReceivedDate(start);
        }
        billService.setStartTime(start);
        billService.setEndTime(end);
        billMapper.insert(billService);

    }

}
